package org.demo.service;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.demo.entity.Role;
import org.demo.entity.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


@Service
public class MyUserDetailsService implements UserDetailsService {

	
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    	// 简单的用户名=密码,除了admin都是user角色
    	User user = new User();
        user.setId(1L);
        user.setUsername(userName);
        user.setPassword(DigestUtils.md5DigestAsHex(userName.getBytes(Charset.defaultCharset())));
        if ("admin".equals(userName)) {
            List<Role> roles = new ArrayList<>();
            Role role=new Role();
            role.setId(1L);
            role.setName("admin");
            roles.add(role);
            user.setAuthorities(roles);
        }else  {
            List<Role> roles = new ArrayList<>();
            Role role=new Role();
            role.setId(2L);
            role.setName("user");
            roles.add(role);
            user.setAuthorities(roles);
        }

        return user;
    }
}
